package org.boot.easyapi.core.service.table.impl;

import org.boot.easyapi.core.framework.jdbc.JdbcRepository;
import org.boot.easyapi.pojo.db.DbDTO;
import org.boot.easyapi.pojo.db.TableDTO;
import org.boot.easyapi.core.controller.view.table.req.TableViewVO;
import org.boot.easyapi.core.cache.CacheRedisDAO;
import org.boot.easyapi.core.service.table.TableViewService;
import org.boot.easyapi.util.CollUtil;
import org.boot.easyapi.util.StrUtil;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

import static org.boot.easyapi.exception.BusinessException.exception;
import static org.boot.easyapi.core.service.table.impl.TableServiceImpl.defaultCreateFields;
import static org.boot.easyapi.core.service.table.impl.TableServiceImpl.defaultFields;

@Service("easyapi-tableViewService")
public class TableViewServiceImpl implements TableViewService {

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Resource(name = "easyapi-cacheRedisDAO")
    private CacheRedisDAO cacheRedisDAO;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(TableViewVO table) {
        checkTableName(table.getTableName());
        //获取数据库类型
        DbDTO db = cacheRedisDAO.getDb();

        //构建数据接口信息
        StringBuilder sql = new StringBuilder("CREATE TABLE " + table.getTableName() + " (");

        // 解析字段信息
        List<TableViewVO.TableFieldVO> fields = table.getFields();
        if(CollUtil.isEmpty(fields)) throw exception("字段信息不能为空！");
        //添加默认建表字段
        for (Map.Entry<String, String> entry : defaultCreateFields.entrySet())  {
            sql.append(entry.getKey()).append(" ").append(entry.getValue()).append(",");
        }
        String dbType = db.getDbType();
        String sqlTypeFiledInfos = null;

        if(dbType.equalsIgnoreCase("mysql")) sqlTypeFiledInfos = getMysqlFiledInfos(fields);
        else if(dbType.equals("kingbase"))  throw exception("暂不支持该数据库类型：" + dbType);
        else throw exception("暂不支持该数据库类型：" + dbType);

        sql.append(sqlTypeFiledInfos);
        sql.delete(sql.length()  - 1, sql.length());  // 移除最后一个逗号和空格
        sql.append(")");

        try{
            jdbcTemplate.execute(sql.toString());
        } catch (Exception e) {
            throw exception("表:" + table.getTableName() + "，创建错误！原因：" + e.getMessage());
        }
    }




    @Override
    public DbDTO getDbType() {
        return cacheRedisDAO.getDb();
    }

    @Override
    public Map<String, List<TableDTO>> getTableList() {
        return cacheRedisDAO.getTables();
    }

    @Override
    public List<TableDTO> getTable(String tableName) {
        return cacheRedisDAO.getTable(tableName, true);
    }



    private String getMysqlFiledInfos(List<TableViewVO.TableFieldVO> fields) {
        if(CollUtil.isEmpty(fields)) return " ";

        StringBuilder sql = new StringBuilder();
        for (TableViewVO.TableFieldVO field : fields) {

            // 跳转默认字段，进入下一次循环
            if(defaultFields.containsKey(field.getName().toLowerCase())){
                continue;
            }
            sql.append(field.getName());
            sql.append(" ");
            switch(field.getType()) {
                case "VARCHAR":
                    sql.append("VARCHAR(").append(field.getSize()).append(")");
                break;
                case "DECIMAL":
                    sql.append("DECIMAL(").append(field.getSize()).append(",").append(field.getPrecision()).append(")");
                break;
                default:
                    sql.append(field.getType());
                break;

            }
            if(!field.getNullable()){
                sql.append(" NOT NULL ");
            }
            if(StrUtil.isNotEmpty(field.getComment())){
                sql.append(" COMMENT '").append(field.getComment()).append("'");
            }
            sql.append(",");
        }
        return sql.toString();
    }

    private void checkTableName(String tableName) {
        List<TableDTO> table = getTable(tableName);
        System.out.println(table);
        if(CollUtil.isNotEmpty(table)){
            throw exception("表:" + tableName + "，已存在！");
        }
    }
}
